package com.lottery.ruok.lottrey.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.CommonFragmentPagerAdapter;
import com.lottery.ruok.lottrey.adapter.CommonFragmentStatePagerAdapter;
import com.lottery.ruok.lottrey.eventbusObject.RefreshRoomStatus;
import com.lottery.ruok.lottrey.eventbusObject.ReloadLotteryEvent;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetWholeCategoryRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetWholeCategoryResponse;
import com.lottery.ruok.lottrey.ui.ShapeIndicatorView;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
/*
*
* 开奖记录
*
* */
public class PrizeMainFragment extends BaseMainFragment {
    @BindView(R.id.custom_indicator)
    ShapeIndicatorView customIndicator;
    @BindView(R.id.tabs)
    TabLayout tabs;
    @BindView(R.id.vpview)
    ViewPager vpView;
    @BindView(R.id.swipe_container)
    SwipeRefreshLayout swipeRefreshLayout;

    private boolean isPrepared;
    private boolean mHasLoadedOnce;
    private View emptyLayout;
    private CommonFragmentStatePagerAdapter adapter;
    private List<BaseFragment> fragments = new ArrayList<>();
    private List<String> titles = new ArrayList<>();
    private int size;

    private void setEmtpyView(){
        if (emptyLayout == null) {
            ViewStub stub = getView().findViewById(R.id.no_net_viewstub);
            View view = stub.inflate();
            emptyLayout = view.findViewById(R.id.no_net_view);
            emptyLayout.setBackgroundResource(R.color.bg_grey);
            emptyLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    getList(true);
                }
            });
        }
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }

        init();

        mHasLoadedOnce = true;
    }

    private void initViewPager(ArrayList<GetWholeCategoryResponse> getWholeCategoryResponses){
        size = getWholeCategoryResponses.size();
        fragments.clear();
        titles.clear();
        for (int i = 0; i <size; i++) {
            fragments.add(ChildPrizeFragment.newInstance());
            titles.add(getWholeCategoryResponses.get(i).getName());
        }
        if(adapter==null){
            adapter = new CommonFragmentStatePagerAdapter(getChildFragmentManager(),fragments,titles);
            vpView.setAdapter(adapter);
            tabs.setupWithViewPager(vpView);
            tabs.setTabMode(TabLayout.MODE_FIXED);
            customIndicator.setupWithTabLayout(tabs);
            customIndicator.setupWithViewPager(vpView);
            vpView.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    fragments.get(position).setSwipState();
                }

                @Override
                public void onPageScrollStateChanged(int state) {
                }
            });
        }else{
            adapter.notifyDataSetChanged();
//            adapter.setNewFragments(fragments);
        }

        if (fragments.size() > 0) {
            vpView.setOffscreenPageLimit(fragments.size());
        }

    }

    private void getList(final boolean isFirst){
        RetrofitBase.getRetrofit().create(GetWholeCategoryRequest.class).getResult(UserInfo.getToken(), 1, 0)
                .compose(RxHelper.<ArrayList<GetWholeCategoryResponse>>handleResult())
                .subscribe(new RxSubscribe<ArrayList<GetWholeCategoryResponse>>(getActivity()) {
                    @Override
                    protected void _onNext(ArrayList<GetWholeCategoryResponse> getWholeCategoryResponses) {
                        if(getActivity() != null) {
                            if(getWholeCategoryResponses.size()>0&&size!=getWholeCategoryResponses.size()){
                                initViewPager(getWholeCategoryResponses);
                            }
                            for (int i = 0; i <fragments.size() ; i++) {
                                BaseFragment fragment = fragments.get(i);
                                fragment.setDatas(getWholeCategoryResponses.get(i));
                            }
                            swipeRefreshLayout.setRefreshing(false);

                            if (emptyLayout != null && emptyLayout.getVisibility() == View.VISIBLE) {
                                emptyLayout.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);

                        swipeRefreshLayout.setRefreshing(false);

                        if(vpView.getAdapter() == null || vpView.getAdapter().getCount() == 0){
                            setEmtpyView();
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return isFirst;
                    }
                });
    }

    private void init() {
        try {
            Field field = ViewPager.class.getDeclaredField("mTouchSlop"); // 通过ViewPager类得到字段，不能通过实例得到字段。
            field.setAccessible(true); // 设置Java不检查权限。
            field.setInt(vpView, 5);
        } catch (Exception e2) {
            e2.printStackTrace();
        }

        getList(true);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getList(false);
                EventBus.getDefault().post(new RefreshRoomStatus());
            }
        });

        vpView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        swipeRefreshLayout.setEnabled(false);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        swipeRefreshLayout.setEnabled(true);
                        break;
                }
                return false;
            }
        });
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.prize_fragment, container, false);

        ButterKnife.bind(this, view);

        isPrepared = true;
        lazyLoad();

        return view;
    }
}